<template>
    <div class="pt-6 sm:pt-8">
        <div class="sm:flex sm:items-center">
            <div class="sm:flex-auto">
                <h1 class="text-base font-semibold text-gray-900 dark:text-gray-100">纪念日提醒</h1>
                <p class="mt-2 text-sm text-gray-700 dark:text-gray-300">管理你的纪念日/倒计时提醒。</p>
            </div>
            <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
                <button type="button"
                    class="block px-3 py-2 text-sm font-semibold text-center text-white bg-indigo-600 rounded-md shadow-xs hover:bg-indigo-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
                    @click.stop="openCreateModal">新增提醒</button>
            </div>
        </div>
        <div class="relative mt-8 -mx-4 bg-white shadow-xs dark:bg-gray-800 rounded-xl sm:-mx-0">
            <div class="overflow-x-auto">
                <table
                    class="w-full min-w-full divide-y divide-gray-100 table-auto dark:text-gray-300 dark:divide-gray-700/60">
                    <thead
                        class="text-xs font-semibold text-gray-500 uppercase border-t border-b border-gray-100 dark:text-gray-400 bg-gray-50 dark:bg-gray-900/20 dark:border-gray-700/60">
                        <tr>
                            <th scope="col" class="px-2 py-3 text-left first:pl-5 last:pr-5 whitespace-nowrap">
                                标题
                            </th>
                            <th scope="col"
                                class="hidden px-2 py-3 text-left first:pl-5 last:pr-5 whitespace-nowrap lg:table-cell">
                                纪念日日期
                            </th>
                            <th scope="col"
                                class="hidden px-2 py-3 text-left first:pl-5 last:pr-5 whitespace-nowrap sm:table-cell">
                                下次纪念日
                            </th>
                            <th scope="col"
                                class="hidden px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap sm:table-cell">
                                周年数
                            </th>
                            <th scope="col"
                                class="hidden px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap sm:table-cell">
                                状态
                            </th>
                            <th scope="col" class="px-2 py-3 text-center first:pl-5 last:pr-5 whitespace-nowrap">
                                倒数天数
                            </th>
                            <th scope="col" class="relative px-2 py-3 first:pl-5 last:pr-5 whitespace-nowrap">
                                <span class="sr-only">编辑</span>
                            </th>
                        </tr>
                    </thead>
                    <tbody class="text-sm divide-y divide-gray-100 dark:divide-gray-700/60">
                        <tr v-for="reminder in reminders" :key="reminder.id">
                            <td
                                class="px-2 py-4 font-medium text-left text-gray-800 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-100">
                                {{ reminder.title }}
                                <dl class="font-normal lg:hidden">
                                    <dd class="mt-1 text-gray-500 truncate dark:text-gray-400">{{
                                        reminder.anniversary_date }}</dd>
                                    <dd class="mt-1 text-gray-500 truncate dark:text-gray-400 sm:hidden">{{
                                        reminder.next_anniversary }}</dd>
                                </dl>
                            </td>
                            <td
                                class="hidden px-2 py-4 text-left text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 lg:table-cell">
                                {{ formatDate(reminder.anniversary_date) }}
                            </td>
                            <td
                                class="hidden px-2 py-4 text-left text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 sm:table-cell">
                                {{ reminder.next_anniversary }}
                            </td>
                            <td
                                class="hidden px-2 py-4 text-center text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 sm:table-cell">
                                {{ reminder.years_passed }}
                            </td>
                            <td
                                class="hidden px-2 py-4 text-center text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400 sm:table-cell">
                                <span :class="reminder.is_active ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'">
                                    {{ reminder.is_active ? '启用' : '停用' }}
                                </span>
                            </td>
                            <td
                                class="px-2 py-4 text-center text-gray-500 first:pl-5 last:pr-5 whitespace-nowrap dark:text-gray-400">
                                {{ reminder.countdown_days }}
                            </td>
                            <td class="px-2 py-4 text-center first:pl-5 last:pr-5 whitespace-nowrap">
                                <div class="flex flex-wrap justify-center gap-2">
                                    <button type="button"
                                        class="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
                                        @click.stop="openEditModal(reminder)">编辑</button>
                                    <button type="button"
                                        class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                                        @click.stop="confirmDelete(reminder)">删除</button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <ModalBasic id="feedback-modal" :modalOpen="showEditModal" :title="editMode ? '编辑提醒' : '新增提醒'">
            <!-- Modal content -->
            <div class="px-5 py-4">
                <div class="space-y-3">
                    <div>
                        <label class="block mb-1 text-sm font-medium" for="name">标题 <span
                                class="text-red-500">*</span></label>
                        <input id="name" class="w-full px-2 py-1 form-input" type="text" v-model="reminderForm.title"
                            required />
                    </div>
                    <div>
                        <label class="block mb-1 text-sm font-medium" for="data">日期 <span
                                class="text-red-500">*</span></label>
                        <!-- Single date mode -->
                        <Datepicker mode="single" @change="handleDateChange"
                            :modelValue="reminderForm.anniversary_date" />
                    </div>
                    <div>
                        <fieldset>
                            <legend class="block mb-1 text-sm font-medium">历法</legend>
                            <div class="mt-2 space-y-2">
                                <label class="flex items-center gap-2">
                                    <input type="radio" name="calendar" v-model="reminderForm.is_lunar" :value="false"
                                        checked
                                        class="w-4 h-4 text-indigo-600 border-gray-300 focus:ring-0 focus:outline-none0">
                                    <span class="text-sm font-medium">公历</span>
                                </label>
                                <label class="flex items-center gap-2">
                                    <input type="radio" name="calendar" v-model="reminderForm.is_lunar" :value="true"
                                        class="w-4 h-4 text-indigo-600 border-gray-300 focus:ring-0 focus:outline-none">
                                    <span class="text-sm font-medium">农历</span>
                                </label>
                            </div>
                        </fieldset>
                    </div>
                    <div>
                        <label class="block mb-1 text-sm font-medium" for="name">状态 </label>
                        <label class="flex items-center gap-2">
                            <input type="checkbox" class="w-4 h-4 text-indigo-600 focus:ring-0 focus:outline-none"
                                v-model="reminderForm.is_active">
                            <span class="text-sm font-medium">启用提醒</span>
                        </label>
                    </div>
                </div>
            </div>
            <!-- Modal footer -->
            <div class="px-5 py-4 border-t border-gray-200 dark:border-gray-700/60">
                <div class="flex flex-wrap justify-end space-x-2">
                    <button
                        class="text-gray-800 border-gray-200 btn-sm dark:border-gray-700/60 hover:border-gray-300 dark:hover:border-gray-600 dark:text-gray-300"
                        @click="closeModal">
                        取消</button>
                    <button
                        class="text-gray-100 bg-gray-900 btn-sm hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-800 dark:hover:bg-white"
                        @click="handleSubmit">
                        {{ editMode ? '保存' : '创建' }}</button>
                </div>
            </div>
        </ModalBasic>


        <ModalBasic id="delete-modal" :modalOpen="showDeleteModal" title="确认删除">
            <div class="px-5 py-4">
                <div class="text-sm">
                    <div class="mb-3 font-medium text-gray-800 dark:text-gray-100">
                        确定要删除 "{{ reminderToDelete?.title }}" 这个纪念日吗？此操作无法撤销。
                    </div>
                </div>
            </div>
            <div class="px-5 py-4 border-t border-gray-200 dark:border-gray-700/60">
                <div class="flex flex-wrap justify-end space-x-2">
                    <button
                        class="text-gray-800 border-gray-200 btn-sm dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500 dark:text-gray-100 dark:hover:text-gray-300"
                        @click="showDeleteModal = false">
                        取消
                    </button>
                    <button class="text-white bg-red-600 btn-sm dark:bg-red-500 hover:bg-red-700 dark:hover:bg-red-600"
                        @click="deleteReminder">
                        确认删除
                    </button>
                </div>
            </div>
        </ModalBasic>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { remindersApi } from '../api/reminder';
import type { Reminder } from '../types/reminder';
import ModalBasic from '../components/ModalBasic.vue'
import Datepicker from '../components/DatePicker.vue'


const reminders = ref<Reminder[]>([]);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editMode = ref(false);
const currentId = ref<number | null>(null);
const reminderToDelete = ref<Reminder | null>(null);

// 分页相关状态
const pagination = reactive({
    page: 1,
    limit: 10,
    total: 0
});

const reminderForm = reactive({
    title: '',
    anniversary_date: '', // ISO 字符串
    is_lunar: false,
    is_active: true,
});

const fetchReminders = async () => {
    try {
        const result = await remindersApi.getReminders(pagination.page, pagination.limit);
        reminders.value = result.items;
        pagination.total = result.total;
    } catch (error) {
        console.error('获取纪念日列表失败：', error);
    }
};

const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
};

const handleDateChange = (selectedDates: Date[]) => {
    if (!selectedDates || selectedDates.length === 0) {
        reminderForm.anniversary_date = '';
        return;
    }

    const date = selectedDates[0];
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    reminderForm.anniversary_date = `${year}-${month}-${day}`;
}

const openCreateModal = () => {
    editMode.value = false;
    resetForm();
    showEditModal.value = true;
};

const openEditModal = (reminder: Reminder) => {
    editMode.value = true;
    currentId.value = reminder.id;
    Object.assign(reminderForm, {
        title: reminder.title,
        anniversary_date: reminder.anniversary_date,
        is_lunar: reminder.is_lunar,
        is_active: reminder.is_active
    });
    showEditModal.value = true;
    console.log(reminderForm)
};

const confirmDelete = (reminder: Reminder) => {
    reminderToDelete.value = reminder;
    showDeleteModal.value = true;
};

const deleteReminder = async () => {
    if (!reminderToDelete.value) return;

    try {
        await remindersApi.deleteReminder(reminderToDelete.value.id);
        await fetchReminders();
        showDeleteModal.value = false;
        reminderToDelete.value = null;
    } catch (error) {
        console.error('删除纪念日失败：', error);
    }
};

const resetForm = () => {
    Object.assign(reminderForm, {
        title: '',
        anniversary_date: '',
        is_lunar: false,
        is_active: true
    });
    currentId.value = null;
};

const closeModal = () => {
    showEditModal.value = false;
    resetForm();
};

const handleSubmit = async () => {
    try {
        if (editMode.value && currentId.value) {
            await remindersApi.updateReminder(currentId.value, reminderForm);
        } else {
            console.log(reminderForm)
            await remindersApi.createReminder(reminderForm as Reminder);
        }
        await fetchReminders();
        closeModal();
    } catch (error) {
        console.error('保存失败：', error);
    }
};

// 分页改变处理
const handlePageChange = (newPage: number) => {
    pagination.page = newPage;
    fetchReminders();
};

onMounted(() => {
    fetchReminders();
});

</script>
